<?php
namespace app\api\controller\contract;

use app\api\controller\Base;
use app\api\controller\mytool\Pagr;
use app\api\controller\mytool\Sendmessage;
use app\api\controller\rebate\Rebate;
use app\common\model\rebate\RebateList;
use app\common\model\company\Company;
use app\common\model\company\Contract;
use app\common\model\company\ContractDetails;
use app\common\model\company\ContractTemp;
use app\common\model\coll\Collection;
use app\common\model\orderhawa\HawaList;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use think\facade\Env;
use think\File;

class Contractbuss extends Base
{
    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(201002);
    }

    /**
     * 临期合同
     * @return [type] [description]
     */
    public function deadlinelist(){
        $data = input('get.');
        $data['Type'] = 'contract';
        $data = init_where($data);
        $list = Contract::deadlinelist($data,'buss');
        foreach ($list['list'] as $key => $value) {
            if(empty($value['companyinfo']['Name'])){
                $list['list'][$key]['Name'] = '暂未完善名称';
            }else{
                $list['list'][$key]['Name'] = $value['companyinfo']['Name'];
            }
            if(empty($value['bussinfo']['Name'])){
                $list['list'][$key]['BussName'] = '暂未完善名称';
            }else{
                $list['list'][$key]['BussName'] = $value['bussinfo']['Name'];
            }
        }
        $list['tr']['title']  = ['产废单位','到期时间','合同状态','查看','剩余天数','签约人'];
        $list['tr']['key'] = ['Name','EndTime','State','ContractId','deadlineday','BussName','BussName'];
        $list['tr']['show']=[true,true,true,true,true,true,false];
        return myok($list);
    }

	/**
	 * 获取合同列表
	 * @param Contract $contract
	 * @return \think\response\Json
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function selectContract(Contract $contract)
	{
		$param = $this->request->get();
		$lists = $contract->contractLists(2, $param['CompanyId'], '');
		return myok($lists);
	}
    /**
     * 获取企业列表
     * @return [type] [description]
     */
    public function getcompanylist()
    {
        $key   = trim(input('searchkey'));
        if($key=="%"){return moerr('非法参数');}
        $idata = input('get.');
        if (empty($idata['lat'])) {
            //没有定位直接显示关键词
            $sdata = ['where' => [['Name', 'like', '%' . $key . '%']]];

        } else {
            $sdata['field'] = [str_distance($idata['lat'], $idata['lon'])];
            $sdata['order'] = 'distance';
            if (!empty($key)) {
                //有定位有关键词的
                $sdata['where'] = [['Name', 'like', '%' . $key . '%']];
            } else {
                //没有的默认为初始化
                $sdata['limit'] = '6';
            }
        }
        $sdata['Type'] = 'company';
        $data          = Company::usergetlist($sdata, 'buss', false);
        return myok($data);
    }
    
    /**
     * 获取选择的收集单位信息
     * @return [type] [description]
     */
    public function getcreateinfo()
    {
        $id  = input('id');
        $cid = input('cid');
        if (empty($id)) {
            return myerr('没有找到产废单位信息');
        }
        if (!empty($cid)) {
            $data = Contract::getinfo($cid, 'buss');
            if (!$data['code']) {
                return myerr($data['msg']);
            }
            $data = $data['msg'];
        }
        $sdata['Type']        = 'contract';
        $sdata['where']       = [['CompanyId', $id]];
        $data['contractlist'] = Contract::usergetlist($sdata, 'buss', false);
        //产废单位公司信息
        $data['companyinfo']  = Company::user_getinfo($id);
        //产废单位财务信息
        $data['companycoll'] = Collection::get_company_info($id);
        //收集单位信息
        $user = UserModel::getinfo();//收集员信息
        $data['mycompanyinfo']=['UserName'=>$user['Name'],'UserTel'=>$user['Iphone'],'Address'=>COMPANYALLNAME.COMPANYADDRESS];

        //服务费信息
        if(get_config_value('switch_Rebate')){
            $rebate = new RebateList();
            $data['rebate'] = $rebate->get_view_info($cid,'contract');
        }
        

        $ordernumber = Contract::order('ContractId desc')->value('OrderNumber');
        $data['end_contract_number'] = $ordernumber;

        $data['contract_ordernumber_control'] = Contract::contract_ordernumber_control();
        $data['StateList']    = Contract::STATEARRAY;

        //获取合同模板
        if(get_config_value('has_contract_temp')){
            $data['ContractTemp'] = ContractTemp::get_create_list();
        }else{
            $data['ContractTemp'] = [];
        }
        return myok($data);
    }

    /**
     * 创建合同信息
     * @return [type] [description]
     */
    public function create()
    {
        $data = input('post.');
        //处理合同详情数据
        if(!empty($data['ContractDetails'])){
            $data['ContractDetails'] = json_array($data['ContractDetails'],true);
        }
        //检测是否缺少关键数据
        foreach ($data['ContractDetails'] as $key => $value) {
            if(empty($value['GoodId'])||empty($value['GoodName'])){
                return myerr('参数错误');
            }
        }
        //新增逻辑
        if (empty($data['cid'])) {
            $hawa = Contract::screate($data);
            if (!$hawa['code']) {
                return myerr($hawa['msg']);
            }
            //判断是否需要增加服务费信息
            if(!empty($data['rebateLimit'])){
                $rebate = new Rebate();
                $rebate->createlist_self('contract',$hawa['msg']->ContractId,$data['rebateLimit'],$data['rebateImg'],$data['rebateNote']);
            }
            //由通知逻辑去判断是否要通知用户
            Sendmessage::Contract(1, $hawa['msg']->ContractId, $hawa['msg']);
            return myok($hawa['msg']->ContractId);
        } else {
            //修改逻辑
            $cid   = $data['cid'];
            $cdata = Contract::getinfo($cid, 'buss');
            if (!$cdata['code']) {
                return myerr($cdata['msg']);
            }
            $cdata = $cdata['msg'];
            if ($cdata['State'] == Contract::STATEOK && !Rolepower::ispower(204004)) {
                return myerr('合同已审核无法修改');
            }
            $rdata       = [];
            $rdata['id'] = $cid;
            $filed = ['OrderNumber','CompanyId','StartTime','EndTime','ContractCost','UpImg','UpNote','PartyAContact','PartyAContactMobile','PartyBMailingAddress','PartyBContact','PartyBContactMobile','Identifier','Name','Address','Mobile','Bank','BankNum','BankCode','UniversalDisposal','DisposalFee','DefaultPrice','ShipNum','ShipMoney','SettleRemark','PartyAMailingAddress','TempId'];
            foreach ($filed as $key => $value) {
                if(isset($data[$value])){
                    $rdata[$value]  = $data[$value];
                }
            }
            //判断是否有绑定用户，若没绑定直接跳转到待会计确认页面
            $companyinfo = Company::get($cdata['CompanyId']);
            if (empty($companyinfo['UserId'])) {
               $rdata['State'] = Contract::STATECONFRIM;
            } else {
            	$rdata['State'] = Contract::STATEINT;
            }
            //修改合同详情信息
            //删除之前关联数据
            ContractDetails::where('ContractId',$cid)->delete();
            //增加新的关联数据
            ContractDetails::screate($cid,$data);
            //修改主表信息
            Contract::user_reinfo($rdata);
            //判断是否需要增加服务费信息
            if(!empty($data['rebateLimit'])){
                $rebate = new Rebate();
                $rebate->createlist_self('contract',$rdata['id'],$data['rebateLimit'],$data['rebateImg'],$data['rebateNote']);
            }
            Sendmessage::Contract(4, $rdata['id'], $cdata);
            return myok($rdata['id']);
        }
    }

    /**
     * 删除合同
     * @return [type] [description]
     */
    public function delete()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少重要参数');
        }
        $cdata = Contract::getinfo($id, 'buss');
        if (!$cdata['code']) {
            return myerr($cdata['msg']);
        }
        $cdata = $cdata['msg'];
        if ($cdata['State'] == Contract::STATEOK) {
            return myerr('合同已审核无法修改');
        }
        $rdata['id']    = $id;
        $rdata['State'] = Contract::STATEDELETE;
        Contract::user_reinfo($rdata);
        return myok('合同删除成功');
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    function list() {
        $data         = input('get.');
        $data['Type'] = 'contract';
        $data         = init_where($data);
        $list         = Contract::usergetlist($data, 'buss');

        foreach ($list['list'] as $key => $value) {
            if (empty($value['companyinfo']['Name'])) {
                $list['list'][$key]['Name'] = '暂未完善名称';
            } else {
                $list['list'][$key]['Name'] = $value['companyinfo']['Name'];
            }
        }
        $list['tr']['title'] = ['产废单位', '下单时间', '订单状态', '查看'];
        $list['tr']['key']   = ['Name', 'CreateTime', 'State', 'ContractId'];
        return myok($list);
    }

    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        //合同信息
        $data = Contract::getinfo($id, 'buss');
        if (!$data['code']) {
            return myerr($data['msg']);
        }
        $data              = $data['msg'];
        //已经签署的合同列表
        $sdata['Type']        = 'contract';
        $sdata['where']       = [['CompanyId', $data['CompanyId']]];
        $data['contractlist'] = Contract::usergetlist($sdata, 'buss', false);
        //服务费信息
        if(get_config_value('switch_Rebate')){
            $rebate = new RebateList();
            $data['rebate'] = $rebate->get_view_info($id,'contract');
        }
        //公司电话
        $data['CELLPHONE'] = CELLPHONE;
        return myok($data);
    }
    /**
     * 接单
     * @return [type] [description]
     */
    public function accept()
    {
        $id   = input('id');
        $data = HawaList::liststate($id);
        if (empty($data)) {
            return myerr('没有找到需要的订单');
        }
        $data = $data['msg'];
        if ($data['State'] !== HawaList::STATEWAIT) {
            return myerr('目前订单状态无法接单');
        }
        $rdata = ['State' => HawaList::STATEWAITOK, 'id' => $id];
        HawaList::user_reinfo($rdata);
        return myok('已接单');
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'hawa' || !$type == 'buss' || !$type == 'acco' || !$type == 'contract') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\contract\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/contract/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
